package cn.linkstudy.service.impl;

import cn.linkstudy.service.DeepSeekService;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeepSeekServiceImpl implements DeepSeekService {
    private static final Logger logger = LoggerFactory.getLogger(DeepSeekServiceImpl.class);

    @Value("${dashscope.api-key}")
    private String apiKey;

    @Value("${dashscope.model}")
    private String model;

    /**
     * 流式输出AI回复和思考过程
     */
    public String streamChat(String userMessage) {
        StringBuilder reasoningContent = new StringBuilder();
        StringBuilder finalContent = new StringBuilder();
        boolean[] isFirstPrint = { true };

        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(userMessage)
                    .build();

            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(Arrays.asList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .incrementalOutput(true)
                    .build();

            Flowable<GenerationResult> result = gen.streamCall(param);
            result.blockingForEach(message -> {
                String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
                String content = message.getOutput().getChoices().get(0).getMessage().getContent();

                if (reasoning != null && !reasoning.isEmpty()) {
                    reasoningContent.append(reasoning);
                    if (isFirstPrint[0]) {
                        System.out.println("====================思考过程====================");
                        isFirstPrint[0] = false;
                    }
                    System.out.print(reasoning);
                }

                if (content != null && !content.isEmpty()) {
                    finalContent.append(content);
                    if (!isFirstPrint[0]) {
                        System.out.println("\n====================完整回复====================");
                        isFirstPrint[0] = true;
                    }
                    System.out.print(content);
                }
            });

            // 返回拼接结果（你也可以自定义返回对象）
            return "【思考过程】\n" + reasoningContent + "\n【回复内容】\n" + finalContent;
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("调用百炼大模型失败: {}", e.getMessage());
            e.printStackTrace();
            return "调用百炼大模型失败：" + e.getMessage();
        }
    }

    @Override
    public String chat(String message) {
        // 兼容原有接口，直接调用流式方法
        return streamChat(message);
    }

    @Override
    public String chatWithMessages(List<Map<String, String>> messages) {
        try {
            Generation gen = new Generation();
            // 将messages转为DashScope Message对象
            java.util.List<Message> msgList = messages.stream().map(m -> Message.builder()
                    .role(m.get("role"))
                    .content(m.get("content"))
                    .build()).collect(Collectors.toList());

            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(msgList)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();

            GenerationResult result = gen.call(param);
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("调用百炼大模型失败: {}", e.getMessage());
            e.printStackTrace();
            return "调用百炼大模型失败：" + e.getMessage();
        }
    }
}